#!/usr/local/bin/python2.7
import settings
import urllib2
import os
import time

def check(url=settings.URL):
    try:
        response = urllib2.urlopen(url, timeout=settings.URL_TIMEOUT)
	data = response.read()
        code = response.getcode()
	if code != 200:
	    return False
	    
	if not settings.NEED_STRING: return True
	return settings.NEED_STRING in data
    except Exception, ex:
	print ex
	pass
    return False
    
def email(mess, subject=settings.SMTP_SUBJ, email_to=settings.SMTP_TO, email_from=settings.SMTP_FROM, host=settings.SMTP_HOST, port=settings.SMTP_PORT):
#def send_email(mess)
    import smtplib
    mess = "From: {0}\nTo: {1}\nSubject: {2}\n\n{3}".format(email_from, ", ".join(email_to), subject, mess)
    smtp = smtplib.SMTP(host, port)
    smtp.sendmail(email_from, email_to, mess)

def get_uptime():
    file = open('/proc/uptime')
    line = file.read()
    file.close()
    uptime, idle = line.split(' ')
    return int(float(uptime))
    
def main(url=settings.URL, pause=settings.PAUSE, reload_command=settings.RELOAD_COMMAND, reboot_command=settings.REBOOT_COMMAND, min_uptime=settings.MIN_UPTIME):
    if check(): return 'OK'
    time.sleep(pause)
    if check(): return 'PAUSE'
    email('Server reload')
    os.system(reload_command)
    time.sleep(pause)
    if check(): return 'RELOAD'
    
    uptime = get_uptime()
    if uptime < min_uptime:
	mess = 'Need reboot, but current uptime %s less than min_uptime %s' % (uptime, min_uptime)
	print mess
	email(mess)
	return
    
    email('Server reboot')
    os.system(reboot_command)
    return 'REBOOT'
    
if __name__ == '__main__':
    print main()